package cn.maihe.elg.operation.centers.quanzhou.handler.service;

import cn.maihe.elg.operation.centers.epoint.config.EpointCenterInfosConfig;
import cn.maihe.elg.operation.centers.epoint.dto.EpointBaseRespDTO;
import cn.maihe.elg.operation.centers.epoint.handler.EpointCenterTradeService;
import cn.maihe.elg.operation.centers.quanzhou.dto.handler.QuanzhouApplyReqDTO;
import cn.maihe.elg.operation.centers.quanzhou.dto.handler.QuanzhouApplyRespDTO;
import cn.maihe.elg.operation.centers.supports.CenterTradeContext;
import cn.maihe.elg.operation.centers.supports.annotation.CenterTradeService;
import cn.maihe.elg.operation.model.enums.CenterNoEnum;
import cn.maihe.elg.operation.model.enums.CenterProviderEnum;
import cn.maihe.elg.operation.model.enums.TradeType;
import cn.maihe.elg.operation.model.enums.AcceptOrderStatus;
import cn.maihe.elg.operation.model.enums.InstitutionOrgCodeEnum;
import cn.maihe.elg.operation.repository.entity.AcceptOrderInfoDO;
import cn.maihe.elg.operation.repository.entity.GuaranteeInstitutionDO;
import cn.maihe.elg.operation.service.order.AcceptOrderInfoService;
import cn.maihe.elg.operation.supports.bank.cmb.util.CashServiceUtil;
import cn.maihe.elg.operation.supports.system.ElgResourceService;
import cn.maihe.elg.operation.utils.IdGenerate;
import cn.maihe.elg.operation.utils.DateUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Description 泉州中心投保申请服务
 * @Author xxx
 * @Date 2025/08/31
 */
@CenterTradeService(
        provider = CenterProviderEnum.EPOINT,
        centerNo = CenterNoEnum.EPOINT_QUANZHOU,
        tradeType = TradeType.baohanapply,
        reqClass = QuanzhouApplyReqDTO.class,
        respClass = EpointBaseRespDTO.class
)
@Slf4j
public class QuanzhouBaohanApplyService extends EpointCenterTradeService<QuanzhouApplyReqDTO, QuanzhouApplyRespDTO> {

    public QuanzhouBaohanApplyService(EpointCenterInfosConfig centerInfosConfig) {
        super(centerInfosConfig);
    }

    @Override
    protected void verifyParam(CenterTradeContext<QuanzhouApplyReqDTO, QuanzhouApplyRespDTO> context) {
        super.verifyParam(context);
        QuanzhouApplyReqDTO req = context.getReq();

        if (req == null) {
            throw new IllegalArgumentException("请求参数不能为空");
        }

        if (!StringUtils.hasText(req.getCnewguid())) {
            throw new IllegalArgumentException("业务流水号不能为空");
        }

        if (!StringUtils.hasText(req.getCprojectname())) {
            throw new IllegalArgumentException("项目名称不能为空");
        }

        if (!StringUtils.hasText(req.getCownerunit())) {
            throw new IllegalArgumentException("业主单位不能为空");
        }

        log.info("泉州中心投保申请参数验证通过，业务流水号: {}", req.getCnewguid());
    }

    @Resource
    private AcceptOrderInfoService acceptOrderInfoService;

    @Resource
    private ElgResourceService elgResourceService;

    @Value("${cn.maihe.elg.auto-create-sub-account:true}")
    private boolean autoCreateSubAccount;

    @Override
    public QuanzhouApplyRespDTO processService(CenterTradeContext<QuanzhouApplyReqDTO, QuanzhouApplyRespDTO> context) {
        AcceptOrderInfoDO acceptOrderInfoDO = buildAcceptOrderInfo(context);
        return buildResp(acceptOrderInfoDO);
    }

    private AcceptOrderInfoDO buildAcceptOrderInfo(CenterTradeContext<QuanzhouApplyReqDTO, QuanzhouApplyRespDTO> context) {
        QuanzhouApplyReqDTO req = context.getReq();
        long centerId = context.getCenterId();
        long orgId = context.getOrgId();
        InstitutionOrgCodeEnum institutionOrgCodeEnum = InstitutionOrgCodeEnum.resolve(context.getOrgCode());
        GuaranteeInstitutionDO institutionDO = getInstitutionIdByCode(institutionOrgCodeEnum);
        String acceptOrderNo = IdGenerate.genAcceptOrderNo(context.getCenterNoEnum());

        String subAccount = null;
        if (!autoCreateSubAccount) {
            subAccount = new java.text.SimpleDateFormat("MMddHHmmss").format(new Date());
        }

        subAccount = CashServiceUtil.subAccountCreateResult(subAccount);
        if (StringUtils.isEmpty(subAccount)) {
            throw new RuntimeException("记账子单元创建异常");
        }

        // 构建加密数据
        JSONObject ciphertext = new JSONObject();
        ciphertext.put("cnewguid", req.getCnewguid());
        ciphertext.put("centerprisename", req.getCenterprisename());
        ciphertext.put("centerprisenamecode", req.getCenterprisenamecode());
        ciphertext.put("cprojectname", req.getCprojectname());
        ciphertext.put("cprojectno", req.getCprojectno());
        ciphertext.put("cbidid", req.getCbidid());
        ciphertext.put("cbidname", req.getCbidname());
        ciphertext.put("cownerunit", req.getCownerunit());
        ciphertext.put("cownerunitcode", req.getCownerunitcode());
        ciphertext.put("fbidtime", req.getFbidtime());
        ciphertext.put("endtime", req.getEndtime());
        ciphertext.put("fmarginamount", req.getFmarginamount());
        ciphertext.put("frate", req.getFrate());
        ciphertext.put("minpremium", req.getMinpremium());
        ciphertext.put("fpremium", req.getFpremium());
        ciphertext.put("zbwjfile", req.getZbwjfile());
        ciphertext.put("reckonprice", req.getReckonprice());
        ciphertext.put("citycode", req.getCitycode());
        ciphertext.put("tbyxq", req.getTbyxq());
        ciphertext.put("tendernoticeurl", req.getTendernoticeurl());

        AcceptOrderInfoDO curAcceptOrder = AcceptOrderInfoDO.builder()
                .centerId(centerId).orgId(orgId)
                .guaranteeNo(IdGenerate.genGuaranteeNo(institutionDO.getInstitutionCode()))
                .centerOrderId(req.getCnewguid())
                .centerOrderTime(DateUtil.getDatetime())
                .acceptOrderNo(acceptOrderNo)
                .institutionId(institutionDO.getId())
                .ciphertext(ciphertext.toJSONString())
                .subAccount(subAccount)
                .clientId(req.getPlatformcode())
                .status(AcceptOrderStatus.WAIT_PAY.getStatus())
                .build();

        return acceptOrderInfoService.saveOrUpdateAcceptOrderInfo(curAcceptOrder);
    }

    private QuanzhouApplyRespDTO buildResp(AcceptOrderInfoDO acceptOrderInfoDO) {
        QuanzhouApplyRespDTO resp = new QuanzhouApplyRespDTO();
        resp.setCode("1");
        resp.setMessage("投保申请成功");

        // 构建跳转链接，根据接口要求返回payurl
        String payUrl = elgResourceService.buildElgFrontUrl("/#/applyOrder?ordersn=" + acceptOrderInfoDO.getAcceptOrderNo());
        resp.setPayurl(payUrl);

        log.info("泉州中心投保申请处理完成，业务流水号: {}, 跳转链接: {}", acceptOrderInfoDO.getCenterOrderId(), payUrl);
        return resp;
    }


}